package net.vkits.controller;

import net.vkits.auth.application.UserApplicationService;
import net.vkits.common.Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * Created by ethan-liu on 16/4/4.
 */
@Controller
@RequestMapping("/changePassword")
public class ChangePasswordController {

    @Resource
    UserApplicationService userApplicationService;

    @RequiresAuthentication
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView changePassword() {
        String username = Utils.getUsername(SecurityUtils.getSubject()).orElse("Null");
        ModelMap modelMap = new ModelMap();
        modelMap.put("treeview", "userInfo");
        modelMap.put("sidebar", "changePassword");
        modelMap.put("currentUser", username);
        return new ModelAndView("/changePassword", modelMap);
    }

    @RequiresAuthentication
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView doChangePassword(@RequestParam(value = "oldPassword") String oldPassword,
                                         @RequestParam(value = "newPassword") String newPassword,
                                         @RequestParam(value = "confirmPassword") String confirmPassword) {
        String username = Utils.getUsername(SecurityUtils.getSubject()).orElse("Null");
        ModelMap modelMap = new ModelMap();
        modelMap.put("treeview", "userInfo");
        modelMap.put("sidebar", "changePassword");
        modelMap.put("currentUser", username);
        String error = null;
        if (StringUtils.isEmpty(oldPassword)
                && StringUtils.isEmpty(newPassword)
                && StringUtils.isEmpty(confirmPassword)) {
            error = "输入参数不能为空";
        }
        if (newPassword.equals(confirmPassword)) {
            userApplicationService.changePassword(username, newPassword);
        } else {
            error = "两次密码不一致";
        }
        modelMap.addAttribute("error", error);
        return new ModelAndView("/changePassword", modelMap);
    }
}
